package com.eightywork.life.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;

import com.eightywork.life.R;
import com.eightywork.life.adapter.PmDetailAdapter;
import com.eightywork.life.model.PmView;
import com.eightywork.life.model.ToUserInfo;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.FooterView;
import com.umeng.analytics.MobclickAgent;

public class PmDetailActivity extends BaseActivity implements OnClickListener {
	private ImageButton backBtn;
	private TextView headTitle;
	private ListView listView;
	//private LinearLayout  llMiddle;
	private EditText etMsg;
	private Button submit;
	private boolean  isLoading = false ;
	private int flag = 0;
	private AsyncTask<?, ?, ?> pmDetailTask, submitTask;
	private String touid, toatoavatar, toverify_type;
	private List<PmView> list;
	private PmDetailAdapter adapter;
	private int page = 0;
	public static PmDetailActivity activity = null;
	private FooterView footView;
	public int firstVisible = -1;
	public static boolean  inDetailView = false;
	private ToUserInfo toUserInfo;
	private long count;
	private Boolean isFromReceive;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_pm_detail);
		activity = this;
		initView();
		initData();
		getPmDetail();
		
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		inDetailView = false;
	}

	@Override
	public void onResume() {		
		super.onResume();
		 inDetailView = true;
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		if (pmDetailTask != null) {
			pmDetailTask.cancel(true);
		}
		
		if (submitTask != null) {
			submitTask.cancel(true);
		}
		super.onDestroy();
	}
	
	public void initView() {
		backBtn = (ImageButton) findViewById(R.id.button_left);
		backBtn.setOnClickListener(this);
		headTitle = (TextView) findViewById(R.id.header_title);
		listView = (ListView) findViewById(R.id.listView_msg);
		etMsg = (EditText) findViewById(R.id.text_msg);
		submit = (Button) findViewById(R.id.button_sbm);
		submit.setOnClickListener(this);
		etMsg.setOnClickListener(this);
	//	llMiddle = (LinearLayout) findViewById(R.id.ll_middle);
		footView = new FooterView(this);
	}
	
	public void initData() {
		initHeader("对话详情");
		isFromReceive = getIntent().getBooleanExtra("isFromReceive", false);
		touid = getIntent().getStringExtra("touid");
		toatoavatar = getIntent().getStringExtra("toatoavatar");
		toverify_type = getIntent().getStringExtra("toverify_type");
		toUserInfo = new ToUserInfo();
		toUserInfo.setTouid(touid);
		toUserInfo.setToatoavatar(toatoavatar);
		toUserInfo.setToverify_type(toverify_type);
		CacheService.setToUserInfo(toUserInfo);
		list = new ArrayList<PmView>();
		adapter = new PmDetailAdapter(context, list);
		listView.addHeaderView(footView.getFooter());
		listView.setAdapter(adapter);
		listView.setOnScrollListener(new ScrollListener());
		listView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				hideKeyBoard(activity);
				return false;
			}
		});	
	}
	
	public void updateDataFromPush(Bundle bundle) {
		String uid = bundle.getString("touid");
		if(uid.equals(touid)){
			PmView pvItem = new PmView();
			long dataline = new Date().getTime()/1000L;
			pvItem.setDateline(String.valueOf(dataline));
			pvItem.setState("success");
			pvItem.setMsgfromuid(uid);					
			pvItem.setMsgfromverifyType(CacheService.getToUserInfo().getToverify_type());
			pvItem.setMsgfromavatar(CacheService.getToUserInfo().getToatoavatar());
			pvItem.setMessage(bundle.getString("msg"));
			list.add(pvItem);
			adapter.notifyDataSetChanged();
			final int notifyid = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					JPushInterface.clearNotificationById(PmDetailActivity.this, notifyid);
				}
			}, 500);
			listView.setSelection(list.size() - 1);
		}
		
	}
	Handler handler = new Handler();
	
	public boolean isEqualCurrentUid(String uid) {
		return uid.equals(touid);
	}
	
	public void getPmDetail() {
		if (isLoading) {
			showMessage("正在请求，请稍后...");
			return;
		}
		pmDetailTask = new PmDetailTask().execute();
	}
	
	class PmDetailTask extends AsyncTask<String, String, String> {
		List<PmView> pdList;
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			isLoading = true;
			page++;
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
	
				pdList = SpaceService.pmView(page + "", "", touid);
				if (isFromReceive) {
					count = SpaceService.noticecount() + CpService.pmcount();
			//		System.out.println("count------in------->" + count);
				}
				
			} catch (MyHttpException e) {
				// TODO Auto-generated catch block
				return e.getErrorMessage();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			
			isLoading = false;
			if (result == null) {
				
				if (pdList != null && pdList.size() > 0) {
					if (pdList.get(0).getMsgtouid().endsWith(CacheService.getSpace().getUid())) {
						//toUserInfo.setTouid(pdList.get(0).getMsgtouid());
						toUserInfo.setToatoavatar(pdList.get(0).getMsgfromavatar());
						toUserInfo.setToverify_type(pdList.get(0).getMsgfromverifyType());
					} else {
						//toUserInfo.setTouid(pdList.get(0).getMsgtouid());		
						toUserInfo.setToatoavatar(pdList.get(0).getMsgtoavatar());
						toUserInfo.setToverify_type(pdList.get(0).getMsgtoverifyType());
					}
					CacheService.setToUserInfo(toUserInfo);
					if (pdList.size() < 5) {
						//listView.removeHeaderView(footView.getFooter());
						footView.showNoData();
					}
					boolean isMore = pdList.size() != 0 ;
					list.addAll(0, pdList);
					System.out.println("list in here ---->" + list.size());
					adapter.notifyDataSetChanged();
					if ( !  isMore ) {
						listView.setSelection(list.size()-1);
					}else {
						listView.setSelection(pdList.size()-1);
					}		  					
				} else  {
			//		listView.removeHeaderView(footView.getFooter());
			//		showMessage("数据加载完成...");
					footView.showNoData();
				}		
		    } else {
		    	listView.removeHeaderView(footView.getFooter());
				showMessage(result);		
		    }
		}
		
	}
	
	private class ScrollListener implements OnScrollListener {

		private int listViewLastItem = 0;
		private boolean isOver = false;
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if ( firstVisible == 0 && scrollState == OnScrollListener.SCROLL_STATE_IDLE)
			{
				// 进行翻页操作+
				if(	 listView.getHeaderViewsCount() == 0 ) {
	//				Toast.makeText(DialogDetailActivity.this, R.string.tips_msg_nodata, Toast.LENGTH_SHORT).show();
				} else {
					getPmDetail();
				}
						
			}
		}
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			// 当listView中没有数据，或者数据超过100条，或者不是10的整数倍（即数据不足）时隐藏“更多”并取消onScroll事件的绑定
//			if (ma.getCount() % 10 > 0 || arrayAdapter.getCount() == 0)
//			{
//				listView.removeFooterView(listViewLoadingView);
//				listView.setOnScrollListener(null);
//			}
			firstVisible = firstVisibleItem;
			if( firstVisibleItem == 0 )
			{
//				Toast.makeText(DialogDetailActivity.this, "h", Toast.LENGTH_SHORT).show();
			}
		}	
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == backBtn) {
	//		System.out.println("count------------->" + count);
			if (isFromReceive) {
				if (count == 0) {
				Intent intent = new Intent(context, IndexActivity.class);
				intent.putExtra("isFromReceive", true);
				context.startActivity(intent);
				 overridePendingTransition(R.anim.push_left_in,R.anim.push_right_out);
			    } else if (count > 0) {
				   Intent intent = new Intent(context, MsgListActivity.class);				  
				   context.startActivity(intent);
				   overridePendingTransition(R.anim.push_left_in,R.anim.push_right_out);
			    } 
			} 	
			PmDetailActivity.this.finish();
		} else if (v == submit) {
			postMsg();
		} else if (v == etMsg) {
		//	System.out.println("list  size == --->" + list.size());
			listView.setSelection(list.size());
		}
		
	}
	
	public void postMsg() {
		String text = etMsg.getEditableText().toString();
		if (text.equals("")) {
			showMessage("请输入信息内容！");
			return;
		}
		etMsg.setText("");
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(etMsg.getWindowToken(), 0);
		submitTask = new SubmitTask(text).execute();
	}
	
	class SubmitTask extends AsyncTask<Integer, Integer, String> {
		
	//	PmView pv;
		PmView pvItem;
		String msg;
		public SubmitTask(String msg) {
			this.msg = msg;
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (list != null) {
				pvItem = new PmView();
				long dataline = new Date().getTime()/1000L;
				pvItem.setDateline(String.valueOf(dataline));
				pvItem.setState("sending");
				pvItem.setMsgfromuid(CacheService.getSpace().getUid());
				pvItem.setMsgfromverifyType(CacheService.getSpace().getVerifyType());
				pvItem.setMsgfromavatar(CacheService.getSpace().getAvatar());
				pvItem.setMessage(msg);
				list.add(pvItem);
				adapter.notifyDataSetChanged();
				listView.setSelection(list.size() - 1);
			} else {
				showProgressDialog("正在加载中...");
			}
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			try {
				CpService.pmsend(touid,msg);
			} catch (MyHttpException e) {
				// TODO Auto-generated catch block
				showMessage(e.getErrorMessage());
				return "fail";
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (result == null) {
				if (list != null && pvItem != null) {
					if (list != null && pvItem != null) {
						pvItem.setState("success");
						adapter.notifyDataSetChanged();
					} else {
						page = 0;
						getPmDetail();
					}
				}
			} else {			
				if (list != null && pvItem != null) {				
					pvItem.setState("fail");
					adapter.notifyDataSetChanged();
					showMessage("发送失败，请重新发送!");
				}
			}
			super.onPostExecute(result);
		}
		
	}

}
